/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  ds18b20_get_temp.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(26/03/25)
 *         Author:  Guo Wenxue <guowenxue@gmail.com>
 *      ChangeLog:  1, Release initial version on "26/03/25 21:26:15"
 *                 
 ********************************************************************************/

#include "ds18b20_get.h"
#include "struct.h"

int get_temper(data_t *data)
{
	int             fd = -1;
	char            buf[128];
	char            *ptr = NULL;
	DIR             *dirp = NULL;
	struct dirent   *direntp = NULL;
	char            w1_path[64] = "/sys/bus/w1/devices/";
	char            chip_sn[32];
	int             found = 0;

	if( !data )
	{
		log_error("ERROR: Invalid input arguments\n");
		return -1;
	}

	dirp = opendir(w1_path);
	if(!dirp)
	{
		log_error("open file %s failure: %s\n",w1_path, strerror(errno));
		return -2;
	}

	while(NULL != (direntp = readdir(dirp)))
	{
		if(strstr(direntp->d_name,"28-"))
		{
			strncpy(chip_sn, direntp->d_name, sizeof(chip_sn));
			found = 1;
			break;
		}
	}
	closedir(dirp);

	if( !found )
	{
		log_error("Can not find ds18b20 chipset\n");
		return -2;
	}

	strncat(w1_path, chip_sn, sizeof(w1_path)-strlen(w1_path));
	strncat(w1_path, "/w1_slave", sizeof(w1_path)-strlen(w1_path));

	if( (fd =open(w1_path,O_RDONLY)) < 0 )
	{
		log_error("open file failure: %s\n",strerror(errno));
		return -2;
	}

	memset(buf, 0, sizeof(buf));

	if(read(fd, buf, sizeof(buf)) < 0)
	{
		log_error("read data from fd = %d failure %s\n", fd, strerror(errno));
		close(fd);
		return -2;
	}

	ptr = strstr(buf, "t=");
	if( !ptr )
	{
		log_error("Can not find t= string\n");
		close(fd);
		return -2;
	}

	ptr = strstr(buf, "t=");
	if( !ptr )
	{
		log_error("ERROR: Can not get temperature\n");
		close(fd);
		return -2;
	}

	ptr += 2;

	data->temper = atoi(ptr)/1000;

	close(fd);
	return 0;
}


/*
int get_sn(data_t *data)
{
	int   len;

	len = sizeof(data->sn);
	memset(data->sn, 0, len);
	snprintf(data->sn, len, "risp%04d", data->sn);
	return 0;
}
*/


long get_time(data_t *data)
{
	time_t      now;
	struct tm   *t;
    long        times;
	int         result;
	int         len;

	now = time(NULL);

	if(now == (time_t)-1)
	{
		return -1;
	}

	t = localtime(&now);
	
	if(t == NULL)
	{
		return -1;
	}

	len = sizeof(data->time);
	memset(data->time, 0, len);
	result = strftime(data->time, len, "%Y-%m-%d %H:%M:%S", t);
	
	if(result == 0)
	{
		return -1;
	}
	times = now;

	return times;
}

